//@login & register
const express=require('express');
const router=express.Router();
const bcrypt=require("bcryptjs");
const gravatar=require("gravatar");
const jwt=require('jsonwebtoken');
const passport=require("passport");

const User=require("../../models/User");
const keys=require("../../config/keys");

const saltRounds = 10;


//$route  Post api/users/register
//@desc   返回的请求的json数据
//@access public
// router.post("/add",(req,res)=>{
//     //查询数据库中是否拥有邮箱
//     User.findOne({name:req.body.email})
//     .then((user)=>{
//         if(user)
//         {
//             return res.status(400).json("名称已被注册！")
//         }
//         else
//         {
//             // let avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});
//             const newUser=new User({
//                 name:req.body.name,
//                 // email:req.body.email,
//                 // avatar:avatar,
//                 password:req.body.password,
//                 role:req.body.role
//             })
//             bcrypt.genSalt(saltRounds, function(err, salt) {
//                 bcrypt.hash(newUser.password, salt, (err, hash)=> {
//                     if(err) throw err;
//                     newUser.password=hash;
//                     newUser.save()
//                         .then(user=>res.json(user))
//                         .catch(err=>console.log(err)); 
//                 });
//             });
//         }
//     })
// })

//$route  Post api/user/login
//@desc   返回的token jwt passport
//@access public
router.post("/login",(req,res)=>{
    // res.setHeader("Access-Control-Allow-Origin",'*');
    const name=req.body.username;
    const password=req.body.password;
    
    User.findOne({name})
    .then(user=>{
        if(!user){
            return res.json({
                code:400,
                message:'用户不存在'
            });
        }
        //密码匹配
        bcrypt.compare(password,user.password)
            .then(isMatch=>{
                if(isMatch){
                    const rule={
                        name:user.name,
                        role:user.role
                    };
                    //生成token
                    jwt.sign(rule,keys.secretOrKet,{expiresIn:3600},(err,token)=>{
                        if(err) throw err;
                        res.json({
                            code:200,
                            data:{
                                token:"Bearer "+ token,
                                avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
                                
                            }
                        });
                    })
                    
                }
                else{
                    return res.json({
                        code:400,
                        message:'密码错误'
                    });
                }
            })
    })
    // const rule={
    //     name:'aaa',
    //     role:'admin'
    // };
    // //生成token
    // jwt.sign(rule,keys.secretOrKet,{expiresIn:3600},(err,token)=>{
    //     if(err) throw err;
    //     res.json({
    //         code:200,
    //         data:{
    //             token:"Bearer "+token,
    //             avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
                
    //         }
    //     });
    // })
})

//$route  Get api/users/current
//@desc   return current user
//@access private


router.post("/add",(req,res)=>{
    User.findOne({name:req.body.name})
    .then((user)=>{
        if(user)
        {
            return res.json({
                code:400,
                message:'该名称已被使用'
            })
        }
        else
        {
            // let avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});
            const newUser=new User({
                name:req.query.name,
                // email:req.body.email,
                // avatar:avatar,
                password:req.query.password,
                role:req.query.role
            })
            
            bcrypt.genSalt(saltRounds, function(err, salt) {
                bcrypt.hash(newUser.password, salt, (err, hash)=> {
                    if(err) throw err;
                    newUser.password=hash;
                    newUser.save()
                    .then(user=>res.json({
                        code:200,
                        data:{
                            name:req.query.name,
                            // email:req.body.email,
                            // avatar:avatar,
                            // password:req.query.password,
                            role:req.query.role
                        }
                    }))
                    .catch(err=>console.log(err)); 
                });
            });
        }
    })
})

router.post("/getList",(req,res)=>{
    const limit=req.query.limit;
    const page=req.query.page;
    User.find({})
    .then(user=>{
        const pageList = user.filter((item, index) => index < limit * page && index >= limit * (page - 1))
        res.json({
            code:200,
            list:pageList,
            total:user.length
        });
    })
})

router.post("/update",(req,res)=>{
    const newUser=new User({
        name:req.body.name,
        // email:req.body.email,
        // avatar:avatar,
        password:req.body.password,
        role:req.body.role
    })
    
    bcrypt.genSalt(saltRounds, function(err, salt) {
        bcrypt.hash(newUser.password, salt, (err, hash)=> {
            if(err) throw err;
            newUser.password=hash;
            User.updateOne({name: newUser.name}, {password:newUser.password, role: newUser.role})
            .then(()=>{
                res.json({
                    code:200,
                    message:'更新成功'
                });
            })
        });
    });
    
})

router.post("/delete",(req,res)=>{
    const name=req.query.name;
    User.deleteOne({name: name})
    .then(()=>{
        res.json({
            code:200,
            message:'删除成功'
        });
    })
})

// router.post("/getInfo",(req,res)=>{
//     res.json({
//         code:200,
//         data:{
//             name:'aaa',
//             role:'管理员'
//         }
//     });
// })
// passport.authenticate("jwt",{session:false})
router.get("/getInfo",passport.authenticate("jwt",{session:false}),(req,res)=>{
    res.json({
        code:200,
        data:{
            name:req.user.name,
            role:req.user.role,
            avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        }
    });
})

module.exports=router;